package com.conghu.crm.web.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.http.HttpResponse;

public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //对于访问非login类资源的请求进行过滤
        System.out.println("进入是否已登陆的过滤");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if(!request.getServletPath().contains("login")){

            HttpSession session = request.getSession(false);
            if(session == null || session.getAttribute("user") == null){
                //重定向方式  让前端重定向到登录页  同时更新前端地址栏的url
                System.out.println("未登录，已发送重定向");
                ((HttpServletResponse)servletResponse).sendRedirect("/crm/login.jsp");
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
